/*
DO NOT MODIFY
*/

#include <winsock2.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <iostream>

#define PORT 6666

// default UDP socket type
#define DEFAULT_PROTO SOCK_DGRAM

int main(int argc, char **argv)
{
    char Buffer[64];
    char *ip_address= "127.0.0.1";
    int port=PORT;
    int retval;
    int fromlen;
    int socket_type = DEFAULT_PROTO;
    struct sockaddr_in local, from;
    WSADATA wsaData;
    SOCKET listen_socket, msgsock;
 
    
    // Request Winsock version 2.2
    if ((retval = WSAStartup(0x202, &wsaData)) != 0)
    {
        fprintf(stderr,"Server: WSAStartup() failed with error %d\n", retval);
        WSACleanup();
        return -1;
    }
    
    local.sin_family = AF_INET;
    local.sin_addr.s_addr = inet_addr(ip_address);
 
    /* Port MUST be in Network Byte Order */
    local.sin_port = htons(port);
    // UDP socket
    listen_socket = socket(AF_INET, socket_type,0);
 
    if (listen_socket == INVALID_SOCKET){
        fprintf(stderr,"Server: socket() failed with error %d\n", WSAGetLastError());
        WSACleanup();
        return -1;
    }
    
	if (bind(listen_socket, (struct sockaddr*)&local, sizeof(local)) == SOCKET_ERROR)
    {
		fprintf(stderr,"Server: bind() failed with error %d\n", WSAGetLastError());
		WSACleanup();
		return -1;
	}
		
    std::string delimiters = " ";

    while(1)
    {
        fromlen =sizeof(from);
        msgsock = listen_socket;
 
        retval = recvfrom(msgsock,Buffer, sizeof(Buffer), 0, (struct sockaddr *)&from, &fromlen);
        //printf("Server: Received datagram from %s\n", inet_ntoa(from.sin_addr
		std::string ret_str(Buffer);
		ret_str = ret_str.substr(0, retval);
		//std::cout << ret_str << std::endl;
        
		
		size_t current;
		size_t next = -1;
		
		//skip first two data catagories
		current = next + 1;
		next = ret_str.find_first_of( delimiters, current );
		current = next + 1;
		next = ret_str.find_first_of( delimiters, current );
		
		//get x
		current = next + 1;
		next = ret_str.find_first_of( delimiters, current );
		std::string x = ret_str.substr( current, next - current );
		
		//get y
		current = next + 1;
		next = ret_str.find_first_of( delimiters, current );
		std::string y = ret_str.substr( current, next - current );

		std::cout << "x: " << x << " y: " << y << std::endl;

        if (retval == SOCKET_ERROR)
        {
            fprintf(stderr,"Server: recv() failed: error %d\n", WSAGetLastError());
            closesocket(msgsock);
            continue;
        }
		

        if (retval == 0)
		{
			printf("Server: Client closed connection.\n");
			closesocket(msgsock);
			continue;
		}
		
	}
	return 0;
}